package com.datatest.riskcheck.tools;

import com.alibaba.fastjson.JSON;
import com.datatest.beans.CreditReportEntity;
import com.datatest.beans.ResultEntity;
import com.sun.rowset.internal.Row;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

@Service
public class ExcelTools {


    public static ResultEntity readSpeColumns(File file, Map<String,String> resultMap) throws BiffException, IOException{
        Map excelMap = new HashMap<String,String>();
        Workbook readwb = null;
        InputStream io = null;
        try {
            io = new FileInputStream(file.getAbsoluteFile());
            readwb = Workbook.getWorkbook(io);
            Sheet readsheet = readwb.getSheet(0);
//        int rsColumns = readsheet.getColumns(); //获取列数
            int rsRows = readsheet.getRows();   //获取行数
            for(int i = 1; i < rsRows;i++){
                    Cell cellName = readsheet.getCell(1,i);
                    //Cell cellValue = readsheet.getCell(1,i);
                    if (cellName.getContents() == null || cellName.getContents().trim().equals("")){
                        break;
                    }
                excelMap.put(cellName.getContents(),"1");
            }
        }finally {
            io.close();
        }
        return checkData(excelMap,resultMap);
    }

    private static ResultEntity checkData(Map excelMap,Map<String,String> resultMap) {
        CreditReportEntity creditReportEntity = JSON.parseObject(JSON.toJSONString(resultMap),CreditReportEntity.class);


        ResultEntity resultEntity = new ResultEntity();
        Iterator<Map.Entry<Integer, String>> it =  excelMap.entrySet().iterator();
        Map<String,Object> resultSuccess = new HashMap<>();
        List resultFail = new ArrayList<>();
        while(it.hasNext()){
            Map.Entry<Integer, String> entry = it.next();
            if(resultMap.get(entry.getKey()) == null){  //excel存在引擎返回不存在
                resultFail.add(entry.getKey());
            }else{
                resultSuccess.put(String.valueOf(entry.getKey()),entry.getValue());
            }
        }
        resultEntity.setResultFail(resultFail);
        resultEntity.setResultSuccess(resultSuccess);
        resultEntity.setCreditReportEntity(creditReportEntity);
        return resultEntity;
    }



}
